import React, { useEffect, useRef } from 'react';

const Map = () => {
  const mapRef = useRef(null);
  const ak = '2NosjFmPxIfSwjRcc3mlfo4tWYu5rvNl'; // 替换为你的百度地图 API 密钥
  const containerId = 'map-container';

  useEffect(() => {
    const loadScript = async () => {
      await loadBaiduMapScript(ak);
      initializeMap();
    };

    loadScript();

    return () => {
      // 清理脚本
      const script = document.querySelector(`script[src*="${ak}"]`);
      if (script) {
        document.body.removeChild(script);
      }
    };
  }, [ak]);

  const loadBaiduMapScript = (ak) => {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script');
      script.src = `https://api.map.baidu.com/api?v=3.0&ak=${ak}`;
      script.async = true;
      script.defer = true;
      script.onload = resolve;
      script.onerror = reject;
      document.body.appendChild(script);
    });
  };

  const initializeMap = () => {
    if (window.BMap && mapRef.current) {
      const map = new window.BMap.Map(mapRef.current);
      const point = new window.BMap.Point(116.404, 39.915); // 北京市
      map.centerAndZoom(point, 15);
      map.enableScrollWheelZoom(true);

      // 添加标记
      const marker = new window.BMap.Marker(point);
      map.addOverlay(marker);
    }
  };

  return (
    <div>
      <h1>百度地图示例</h1>
      <div id={containerId} ref={mapRef} style={{ width: '100%', height: '400px' }}></div>
    </div>
  );
};

export default Map;